const cityJson = city;//获得json城市数据
var openedCity = [];//已开通城市数据
var app = new Vue({
    el: '#app',
    data: {
        name: '', //名字
        phone: '', //手机号码
        address: '', //地址
        joincity: '', //城市
        joincityID: '', //城市ID
        descript: '', //描述
        imgList: [], //图片数组
        size: 0,
        checkbox: '',
        userId: 0, //用户id
        isAllowUpload: true, //是否允许上传图片，默认是，多于限定个数为false
        accept: 'image/gif, image/jpeg, image/png, image/jpg', //图片上传类型
        cityList: [], //历史城市数组
        cityAZ: ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"], //字母
        cityResults: null, //城市循环
        scrollAZ: null,
        scrollNow: 0,
        isShow: false,//是否显示城市选择界面
        // openedCity:[],//已经开通的城市数据

    },
    created() {
        if ($.getPara("userId") != "") {
            var userId = $.getPara("userId");
            this.userId = userId;
            //缓存用户ID
            $.setStorage("userId", userId);
        } else {
            if ($.getStorage("userId") && $.getStorage("userId") != "") {
                var userId = parseInt($.getStorage("userId"));
                this.userId = userId;
            }
        }
        this.cityData(); //查询所有城市分页列表
        this.joincitys();//查询已经开通的城市
    },
    mounted () {
       
    },
    methods: {
        //压缩图片方法  
        compress(event, callback) {
            if (typeof (FileReader) === 'undefined') {
                $.toast("当前浏览器内核不支持base64图片压缩", "text");
                //调用上传方式  不压缩  
            } else {
                try {
                    var file = event.currentTarget.files[0];
                    var reader = new FileReader();
                    // $.toast("我正在压缩") 
                    reader.onload = function (e) {
                        var image = $('<img/>');
                        image.on('load', function () {
                            var square = 500;
                            var canvas = document.createElement('canvas');
                            canvas.width = square;
                            canvas.height = square;
                            var context = canvas.getContext('2d');
                            context.clearRect(0, 0, square, square);
                            var imageWidth;
                            var imageHeight;
                            var offsetX = 0;
                            var offsetY = 0;
                            if (this.width > this.height) {
                                imageWidth = Math.round(square * this.width / this.height);
                                imageHeight = square;
                                offsetX = -Math.round((imageWidth - square) / 2);
                            } else {
                                imageHeight = Math.round(square * this.height / this.width);
                                imageWidth = square;
                                offsetY = -Math.round((imageHeight - square) / 2);
                            }
                            context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                            var data = canvas.toDataURL('image/jpeg'); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！

                            //压缩完成执行回调  
                            callback(data);
                            // $.toast("压缩完成") 
                        });
                        image.attr('src', e.target.result);
                    };
                    reader.readAsDataURL(file);
                } catch (e) {
                    // console.log("压缩失败!");
                    $.toast("图片压缩失败，请重试！", "text");
                    //调用上传方式  不压缩  
                }
            }
        },
        //已开通城市列表
        joincitys: function () {
        var that = this;
            $.ajax({
                url:  + "api/substation/city/list",
                type: 'get',
                data: {
                    pageIndex: 1,
                    pageSize: 1000,
                },
                dataType: 'json'
            }).done(function (data, status, xhr) {
                var data = data.data;
                openedCity = data;
                // console.log(openedCity);
            });
        },
        //获取中国所有城市列表
        cityData() {
            // console.log(cityJson);
            //获取所有的城市
            let data = cityJson.data.cities;
            // console.log(data)
            if (data && typeof(data) == "object") {
                let array = [];
                for (let obj in data) {
                    let _obj = {};
                    _obj.cityName = obj;
                    _obj.citysub = data[obj];
                    array.push(_obj);
                    // console.log(_obj.citysub);
                    // console.log(data[obj])
                };
                // console.log(array);
                this.cityResults = array;
                // console.log(this.cityResults);
                // this.setData({ cityResults: array }); //默认展示的城市的数据
                // this.setData({ searchList: array }); //默认用于搜索筛选的数据

            }


        },
        //绑定A-Z所有城市列表
        bindAZ(e) {
            // console.log(e);
            var currentCityName = e;
            // var top = $(this).offset().top;
            // console.log(this);
            var that = this;
            // setTimeout(function(){
                window.location.href = "#"+currentCityName;
            // },1000)
            // $('html, body').animate({scrollTop: $('a[A-Z]').offset().top}, 1000)
            //console.log(e.currentTarget.dataset.id, 'currentCityName')
            //放入A-Z的scrollTop参数
            // if (that.data.scrollAZ == null) {
            //     wx.createSelectorQuery().selectAll('.city-item-A-Z').fields({
            //         dataset: true,
            //         size: true,
            //         rect: true
            //     }, function(res) {
            //         res.forEach(function(re) {
            //             if (currentCityName == re.dataset.cityname) {
            //                 wx.pageScrollTo({
            //                     scrollTop: re.top + that.data.scrollNow - 55.5,
            //                     duration: 0
            //                 })
            //             }
            //         })
            //     }).exec();
            // } else {
            //     this.data.scrollAZ.forEach(function(re) {
            //         if (currentCityName == re.dataset.cityname) {
            //             wx.pageScrollTo({
            //                 scrollTop: re.top + that.data.scrollNow - 55.5,
            //                 duration: 0
            //             })
            //         }
            //     })
            // }
        },
         //选择当前城市
        citySelected: function(e) {
            let _this = this;
            let choseCity = e;
            //遍历已经开通城市 当前选择为已开通 提示
            let cityData = openedCity;
            // console.log(openedCity)
            var flag = true;
            for(let i = 0 ;i<cityData.length;i++){
               
                if(choseCity.name+'站' == cityData[i].name){//当前城市已经开通
                    $.toast("当前城市已经开通，请重新选择","text");
                    flag = false;
                    break;
                    
                }        

            }
            //  debugger;
            if(flag){
                // 获取选中的城市
                var cityNameTemp = choseCity.name;
                _this.joincity = cityNameTemp;
                _this.isShow = false;
            }
        },
        // //获取当前位置
        // onPageScroll: function(e) {
        //     // 获取滚动条当前位置
        //     this.setData({
        //         scrollNow: e.scrollTop
        //     })
        // },
        joinApply(userId, name, mobile, address, cityId, joincity,description, imgList) {
            $.ajax({
                url:"/api/substation/join/apply",
                type: 'post',
                data: {
                    userId: userId, //当前用户ID
                    name: name, //姓名
                    mobile: mobile, //联系方式
                    address: address, //办公地址
                    cityId: cityId, //加盟分站城市ID 不需要的
                    cityName: joincity, //加盟分站城市ID
                    description: description, //描述 
                    imgList: imgList //图片数组 
                },
                success: function (res, textStatus, jqXHR) {
                    if (res.code == 200) {
                        $.toast(res.msg, 'text');
                        setTimeout(function () {
                            // window.history.go(-1);
                             //调用原生返回上一级页面  上一级页面刷新
                            var para={};
                            para.isRefresh = true;  //返回上一页。上一页刷新
                            if (/(Android)/i.test(navigator.userAgent)) { //判断Android
                                //是android系统
                                // alert("Android系统");
                                jsAndroid.appReturn(JSON.stringify(para))
                            } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
                                //默认为iOS系统
                                window.webkit.messageHandlers.appReturn.postMessage(para);
                            } else {
                                //pc
                                window.location.href = para.url;
                                alert("PC浏览器");
                            };
                        }, 1500)
                    }
                    if (res.code == 500) {
                        $.toast(res.msg, 'text');
                    }
                },
                error: function (xhr, textStatus) {}
            })

        },
        //上传图片
        uploadImgs(event) {
            var _event = event;
            var _this = this;
            let reader = new FileReader();
            let img1 = event.target.files[0];
            let type = img1.type; //文件的类型，判断是否是图片  
            let size = img1.size; //文件的大小，判断图片的大小
            var input = input;
            const files = event.target;
            if (this.accept.indexOf(type) == -1) {
                $.toast("请选择gif,jpeg,png,jpg格式图片上传", "text");
                return false;
            } else if (size > 3145728) {
                $.toast("请选择3M以内的图片上传", "text");
                return false;
            } else if (typeof (FileReader) === 'undefined') {
                $.toast("抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！", "text");
            } else {
                _this.compress(event, function (base6464) {
                    var base6464 = base6464;
                    // console.log("图片上传中...")   
                    // console.log(base6464) 
                    $.ajax({
                        url: '/api/common/upload/base64',
                        type: 'post',
                        data: {
                            base64: base6464
                        },
                        dataType: 'json',
                        success: function (response) {
                            if (response.code == 200) {
                                $.toast('恭喜你，图片上传成功', "text");
                                _this.imgList.push(response.data);
                                _this.checkLimit();
                            } else {
                                //失败了
                                // $.toast(response.msg, "text");
                            }
                        }
                    })
                })
            }
        },
        //删除图片
        delPicture(index, row, typeId) {
            //当前记录的下标
            this.idx = index;
            this.typeId = typeId;
            this.imgList.splice(this.idx, 1);
            this.checkLimit();
            $.toast('删除成功', "text");
            this.headImg = []; //清空封面            
        },
        //检查图片是否超过数量规定
        checkLimit() {
            if (this.imgList.length >= 5) { //多于5张
                this.isAllowUpload = false;
            } else {
                this.isAllowUpload = true;
            }
        },
        submit: function () {
            //添加一个强制登录以获取userId
            //获取到userId字段内容并且用户id>0已登录   
            if ($.getPara("userId") != "" && this.userId > 0) {
                var that = this;
                if (this.name === '') {
                    $.toast("请输入加盟人姓名", "text");
                    return false;
                }
                if (this.phone === '') {
                    $.toast("请输入联系电话", "text");
                    return false;
                } else if (!(/^[1][3,4,5,7,8,9][0-9]{9}$/.test(this.phone))) {
                    $.toast("联系人电话输入有误！", "text");
                    return false;
                }
                if (this.address === '') {
                    $.toast("请输入联系地址", "text");
                    return false;

                }
                if (this.descript === '') {
                    $.toast("请输入加盟描述", "text");
                    return false;
                }
                if (this.joincity === '') {
                    $.toast("请选择加盟城市", "text");
                    return false;
                }
                if (this.imgList === '') {
                    $.toast("请上传图片", "text");
                    return false;
                }
                if (this.checkbox === '' || this.checkbox === false) {
                    $.toast("请同意法律条款", "text");
                    return false;
                }
                name = this.name;
                phone = this.phone;
                address = this.address;
                descript = this.descript;
                joincity = this.joincity;
                joincityID = 0;
                imgList = this.imgList;
                var imgList = JSON.stringify(imgList)
                that.joinApply(this.userId, name, phone, address,joincityID, joincity, descript, imgList)
            } else {
                //用户未登录
                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) { //判断iPhone|iPad|iPod|iOS
                    //默认为iOS系统   
                    window.webkit.messageHandlers.appLogin.postMessage(null);
                } else {
                    //pc
                    alert("PC浏览器-appLogin");
                };
            }
        },
        //显示选择城市界面
        showCityPage(){
            this.isShow = true;
        },
    }
})
